public class DeadlockTransfer {
    static class Account {
        private String name;
        private int balance;

        public Account(String name, int balance) {
            this.name = name;
            this.balance = balance;
        }

        public void transfer(Account to, int amount) {
            // 锁定当前账户
            synchronized (this) {
                System.out.println(Thread.currentThread().getName() + " 持有锁: " + this.name);

                // 模拟一些处理时间，增加死锁概率
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                // 锁定目标账户
                synchronized (to) {
                    System.out.println(Thread.currentThread().getName() + " 持有锁: " + to.name);

                    if (this.balance >= amount) {
                        this.balance -= amount;
                        to.balance += amount;
                        System.out.println("转账成功: " + amount + " 从 " + this.name + " 到 " + to.name);
                    } else {
                        System.out.println("余额不足，转账失败");
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Account accountA = new Account("商家A", 1000);
        Account accountB = new Account("客户B", 1000);

        // 线程1：A向B转账200
        Thread thread1 = new Thread(() -> accountA.transfer(accountB, 200), "Thread-AtoB");

        // 线程2：B向A转账300
        Thread thread2 = new Thread(() -> accountB.transfer(accountA, 300), "Thread-BtoA");

        thread1.start();
        thread2.start();

        try {
            thread1.join(3000); // 等待3秒
            thread2.join(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 检查是否死锁（预期会死锁，无法完成输出）
        System.out.println("商家A余额: " + accountA.balance);
        System.out.println("客户B余额: " + accountB.balance);
    }
}